package com.kaka.bus.down.service;

import android.app.IntentService;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.os.Environment;
import android.support.v4.app.NotificationCompat;

import com.kaka.bus.R;
import com.kaka.bus.bean.MyInfo;
import com.kaka.bus.down.bean.Download;
import com.kaka.bus.down.network.DownloadAPI;
import com.kaka.bus.down.network.download.DownloadProgressListener;
import com.kaka.bus.down.utils.StringUtils;
import com.kaka.bus.util.logger.Logger;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.InputStream;

import io.reactivex.subscribers.ResourceSubscriber;

/**
 * Created by JokAr on 16/7/5.
 */
public class DownloadService extends IntentService {
    private static final String TAG = "DownloadService";

    private NotificationCompat.Builder notificationBuilder;
    private NotificationManager notificationManager;

    int downloadCount = 0;

    private String apkUrl = "";

    public DownloadService() {
        super("DownloadService");
    }
    //apk保存的文件
    private File outputFile;

    @Override
    protected void onHandleIntent(Intent intent) {
        //拿到路径
        apkUrl = intent.getStringExtra("url");
        notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        notificationBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.ic_download)
                .setContentTitle("APP更新下载")
                .setContentText("Downloading File")
                .setAutoCancel(true);

        notificationManager.notify(0, notificationBuilder.build());

        download();
    }

    private void download() {
        DownloadProgressListener listener = (bytesRead, contentLength, done) -> {
            //不频繁发送通知，防止通知栏下拉卡顿
            int progress = (int) ((bytesRead * 100) / contentLength);
            if ((downloadCount == 0) || progress > downloadCount) {
                Download download = new Download();
                download.setTotalFileSize(contentLength);
                download.setCurrentFileSize(bytesRead);
                download.setProgress(progress);

                sendNotification(download);
            }
        };
        boolean sdCardExist = Environment.getExternalStorageState()
                .equals(android.os.Environment.MEDIA_MOUNTED);
        if(sdCardExist){
            outputFile = new File(Environment.getExternalStorageDirectory(), "kkqb.apk");
        }

        if (outputFile.exists()) {
            outputFile.delete();
        }

        String baseUrl = StringUtils.getHostName(apkUrl);
        Logger.i(baseUrl);
        //下载
        new DownloadAPI(baseUrl, listener).downloadAPK(apkUrl, outputFile, new ResourceSubscriber<InputStream>() {
            @Override
            public void onNext(InputStream inputStream) {

            }

            @Override
            public void onError(Throwable t) {
                Logger.i("下载失败:"+t.toString());
                EventBus.getDefault().post(new MyInfo<>(new Download(), MyInfo.MyInfoEnum.downerror));
            }

            @Override
            public void onComplete() {
                downloadCompleted();
            }
        });
    }

    private void downloadCompleted() {
        Download download = new Download();
        download.setProgress(100);
        sendIntent(download);

        notificationManager.cancel(0);
        notificationBuilder.setProgress(0, 0, false);
        notificationBuilder.setContentText("下载完成");
        notificationManager.notify(0, notificationBuilder.build());
        /**
         * 下载完成 通知安装版本
         */
        EventBus.getDefault().post(new MyInfo<>(outputFile, MyInfo.MyInfoEnum.installApp));
    }

    private void sendNotification(Download download) {
        sendIntent(download);
        notificationBuilder.setProgress(100, download.getProgress(), false);
        notificationBuilder.setContentText(
                StringUtils.getDataSize(download.getCurrentFileSize()) + "/" +
                        StringUtils.getDataSize(download.getTotalFileSize()));
        notificationManager.notify(0, notificationBuilder.build());
    }

    private void sendIntent(Download download) {
        EventBus.getDefault().post(new MyInfo<>(download, MyInfo.MyInfoEnum.downinfo));
    }

    @Override
    public void onTaskRemoved(Intent rootIntent) {
        notificationManager.cancel(0);
    }
}
